﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Authorization;
using WorkFlowCore.Authorization.JWT;

namespace WorkFlowCore.Framework.Authorization
{
    //实现一个中间件，用于将用户信息写入到Session中
    public class WorkflowSessionMiddleware
    {
        public WorkflowSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        private readonly RequestDelegate _next;
        public async Task InvokeAsync(HttpContext context, IWorkflowSession workflowSession)
        {

            workflowSession.SetUser(GetUser(context));
            await _next(context);
        }


        private User GetUser(HttpContext httpContext)
        {
            if (httpContext == null) new EmptyUser();

            var authenticate = httpContext.AuthenticateAsync().Result;
            if (authenticate.Succeeded)
            {

                try
                {

                    var userInfoStr = authenticate.Principal.Claims.FirstOrDefault(c => c.Type == "user-info").Value;
                    userInfoStr = WebUtility.UrlDecode(userInfoStr);
                    var user =  JsonConvert.DeserializeObject<User>(userInfoStr);

                    if (user.IsManager)
                    {
                        try
                        {

                            userInfoStr = httpContext.Request.Headers["user-info"];
                            userInfoStr = WebUtility.UrlDecode(userInfoStr);
                            var simulateUser = JsonConvert.DeserializeObject<User>(userInfoStr);
                            if (userInfoStr != null && !string.IsNullOrWhiteSpace(simulateUser.Id))
                            {
                                user.Id = simulateUser.Id;
                                user.Name = simulateUser.Name;
                                if(!simulateUser.AppId.IsNullOrWhiteSpace())
                                {
                                    user.AppId = simulateUser.AppId;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            //return new EmptyUser();
                        }
                    }

                    return user;

                }
                catch (Exception)
                {
                    //this.User = new User(user.Id, user.Name);
                }


            }
            return new EmptyUser();
        }

        public bool IsManager(HttpContext httpContext)
        {
            if (httpContext == null) return false;

            var authenticate = httpContext.AuthenticateAsync().Result;
            if (authenticate.Succeeded)
            {
                //这里，如果是通过 管理员账号登录，则从头部 user-info 获取代理的 用户信息，否则，从token凭据中的 user-info 解析用户信息
                var IsManager = authenticate.Principal.Claims.Any(c => c.Type == "ismanager" && c.Value == JWTAuthenticationOptions.ClaimTypesRole_Admin);
                return IsManager;
            }
            return false;
        }
    }


    public class WorkflowAppContextMiddleware
    {
        public WorkflowAppContextMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        private readonly RequestDelegate _next;
        public async Task InvokeAsync(HttpContext context, IWorkflowSession workflowSession,IAppContextManager appContextManager)
        {
            var appid = context.GetContextParameter("appid");
            workflowSession.SetUser(new EmptyUser()
            {
                AppId = appid
            });
            appContextManager.SetAppId(appid);
            await _next(context);
        }
    }
    public static class WorkflowSessionExtension
    {
        //实现一个注册中间件的扩展方法
        public static IApplicationBuilder UseWorkflowSession(this IApplicationBuilder app)
        {
            return app.UseMiddleware<WorkflowSessionMiddleware>();
        }

        public static IApplicationBuilder UseWorkflowAppContext(this IApplicationBuilder app)
        {
            return app.UseMiddleware<WorkflowAppContextMiddleware>();
        }

        //实现一个注册 workflowsession 服务的扩展方法
        public static IServiceCollection AddWorkflowSession(this IServiceCollection services)
        {
            services.AddScoped<IWorkflowSession, DefaultSession>();
            services.AddScoped<IAppContextManager, AppContextManager>();
            return services;
        }
    }

}
